package com.ikingtech.platform.service.system.dict.service.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikingtech.framework.sdk.context.exception.FrameworkException;
import com.ikingtech.framework.sdk.dict.model.DictItemQueryParamDTO;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.dict.entity.DictItemDO;
import com.ikingtech.platform.service.system.dict.exception.DictExceptionInfo;
import com.ikingtech.platform.service.system.dict.mapper.DictItemMapper;

/**
 * @author tie yan
 */
public class DictItemRepository extends ServiceImpl<DictItemMapper, DictItemDO> {

    public static LambdaQueryWrapper<DictItemDO> createWrapper(DictItemQueryParamDTO queryParam, String tenantCode) {
        return Wrappers.<DictItemDO>lambdaQuery()
                .eq(Tools.Str.isNotBlank(queryParam.getDictCode()), DictItemDO::getDictCode, queryParam.getDictCode())
                .like(Tools.Str.isNotBlank(queryParam.getLabel()), DictItemDO::getLabel, queryParam.getLabel())
                .eq(Tools.Str.isNotBlank(queryParam.getValue()), DictItemDO::getValue, queryParam.getValue())
                .eq(null != queryParam.getPreset(), DictItemDO::getPreset, queryParam.getPreset())
                .eq(Tools.Str.isNotBlank(tenantCode), DictItemDO::getTenantCode, tenantCode)
                .and(Tools.Str.isBlank(tenantCode), wrapper -> wrapper.eq(DictItemDO::getTenantCode, Tools.Str.EMPTY).or().isNull(DictItemDO::getTenantCode))
                .orderByDesc(DictItemDO::getCreateTime);
    }

    public String parseFullPath(String parentId, String id) {
        if (Tools.Str.isNotBlank(parentId)) {
            DictItemDO parentEntity = this.getById(parentId);
            if (null == parentEntity) {
                throw new FrameworkException(DictExceptionInfo.PARENT_DICT_ITEM_NOT_FOUND);
            }
            return parentEntity.getFullPath() + "@" + id;
        } else {
            return id;
        }
    }
}
